package com.tsingteng.cosfun.ui.focus;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dingmouren.layoutmanagergroup.viewpager.OnViewPagerListener;
import com.dingmouren.layoutmanagergroup.viewpager.ViewPagerLayoutManager;
import com.pili.pldroid.player.IMediaController;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BasePresenterFragment;
import com.tsingteng.cosfun.bean.AttentRecommendbean;
import com.tsingteng.cosfun.bean.BlindResp;
import com.tsingteng.cosfun.bean.EventBean;
import com.tsingteng.cosfun.bean.FollowBean;
import com.tsingteng.cosfun.bean.FoundAtBean;
import com.tsingteng.cosfun.bean.HomeBean;
import com.tsingteng.cosfun.bean.JoinCostarBean;
import com.tsingteng.cosfun.bean.OpusBean;
import com.tsingteng.cosfun.bean.RecommenResp;
import com.tsingteng.cosfun.bean.SearchResp;
import com.tsingteng.cosfun.bean.VideoSection;
import com.tsingteng.cosfun.bean.VideoSectionBean;
import com.tsingteng.cosfun.callback.AppListener;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.cosfun.CommentListDialogFragment;
import com.tsingteng.cosfun.ui.cosfun.ShareFragment;
import com.tsingteng.cosfun.ui.cosfun.TipOffsActivity;
import com.tsingteng.cosfun.ui.cosfun.adapter.OpusAdapterNew;
import com.tsingteng.cosfun.ui.cosfun.contract.OpusContract;
import com.tsingteng.cosfun.ui.cosfun.contract.ZanContract;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverListener;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverManager;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.RecyclerOnScrollListener;
import com.tsingteng.cosfun.ui.cosfun.presenter.OpusPresenter;
import com.tsingteng.cosfun.ui.costar.CostarActivity;
import com.tsingteng.cosfun.ui.focus.adapter.FocusAttentionAdapter;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.ui.mine.TerminalActivity;
import com.tsingteng.cosfun.ui.mine.adapter.CommonAdapter;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.CommandManager;
import com.tsingteng.cosfun.utils.FileDownUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.NetUtils;
import com.tsingteng.cosfun.utils.ShareUtils;
import com.tsingteng.cosfun.utils.StringUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.utils.VideoUtils;
import com.tsingteng.cosfun.widget.MyRecycleView;
import com.tsingteng.cosfun.widget.ObservableListView;
import com.tsingteng.cosfun.widget.dialog.DownLoadProgressDialog;
import com.tsingteng.cosfun.widget.dialog.LongPressShowDialog;
import com.tsingteng.cosfun.widget.dialog.ProgressDialog;
import com.tsingteng.cosfun.widget.dialog.ShowNetStatusDialog;
import com.tsingteng.cosfun.widget.view.MySwipeRefreshLayout;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.litepal.util.LogUtil;
import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class FocusOpusFragmentNew extends BasePresenterFragment<OpusPresenter, OpusContract.IOpusView> implements ObserverListener,
        OpusContract.IOpusView, ZanContract.IZanView, OpusAdapterNew.OnItemClickLisenter, ShareFragment.OnShareItemClickLisenter, ShareUtils.ShareListener, LongPressShowDialog.OnItemClickListener, CommentListDialogFragment.CommLisenter
        ,FocusAttentionAdapter.FocusAttentListener
        ,ShowNetStatusDialog.OnItemClickListener
        ,View.OnClickListener{
    private String TAG = this.getClass().getSimpleName();
    private RecyclerView recyclerView = null;
    private ViewPagerLayoutManager mLayoutManager;
    private OpusAdapterNew mAdapter;
    private int pageNo = 1;
    private int currentPosition = 0;
    private int lastPosition = 0;
    List<OpusBean> videoList = null;
    DownLoadProgressDialog.Builder builder = null;
    DownLoadProgressDialog downLoadProgressDialog = null;
    private ArrayList<String> urlPath;
    private AudioManager audio = null;
    private ProgressBar progressBar = null;
    private ProgressBar v_progressBar = null;
    private IMediaController.MediaPlayerControl mPlayer;
    private static final int SHOW_PROGRESS = 2;
    private LongPressShowDialog.Builder longBulider;
    private LongPressShowDialog longPressShowDialog;
    private ShowNetStatusDialog.Builder netBuilder = null;
    private ShowNetStatusDialog netStatusDialog = null;
    private MySwipeRefreshLayout refreshLayout = null;
    private boolean isRefresh = false;

    private RelativeLayout cosRel = null;
    private CircleImageView cosCircleImageView = null;
    private CircleImageView opus_item_view_user_img1 = null;
    private ImageView cosGuanzhu = null;
    private TextView cosTag = null;
    private List<VideoSection> videoSectionList = null;
    private ColorMatrixColorFilter grayColorFilter = null;
    private TextView empty_tv;
    private LinearLayout lin_empty;
    private ImageView back = null;
    private boolean isCanClickJoin = true;//是否可以点击合拍按钮
    private ProgressDialog progressDialog;
    private OpusBean mOpusBean;
    private ListView recycler_view;
    private FocusAttentionAdapter mAttentAdapter;
    private ImageView mCosfunIv;
    private boolean canPlay = false;
    private String[] mProfileId;
    private int manager;

    @Override
    protected void initView() {
        super.initView();
        recyclerView = rootView.findViewById(R.id.focus_opus_list);
        mCosfunIv = rootView.findViewById(R.id.cosfun_iv);
        mCosfunIv.setVisibility(View.VISIBLE);
        progressBar = rootView.findViewById(R.id.play_progress);
        v_progressBar = rootView.findViewById(R.id.volume_progress);
        empty_tv = rootView.findViewById(R.id.empty_tv);
        recycler_view = rootView.findViewById(R.id.recycler_view);
        mLayoutManager = new ViewPagerLayoutManager(getActivity(), OrientationHelper.VERTICAL);
        videoList = new ArrayList<>();
        videoSectionList = new ArrayList<>();
        urlPath = new ArrayList<>();
        mAdapter = new OpusAdapterNew(getActivity(), 2, videoList, 0, this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);
        refreshLayout = rootView.findViewById(R.id.fragment_focus_refresh);
        lin_empty = rootView.findViewById(R.id.lin_empty);
        mCosfunIv.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                if (VideoUtils.getLocalUserLikeCount() <= 0) {
//                    Toast.makeText(getActivity(), "这是第一个哦", Toast.LENGTH_SHORT).show();
//                    refreshLayout.setRefreshing(false);
//                    return;
//                }
                playerPause(currentPosition);
                isRefresh = true;
                videoList.clear();
                pageNo = 1;
                mPresenter.getFocusOpusList(pageNo + "");
            }
        });

        initListener();
        ObserverManager.getInstance().add(this);
        builder = new DownLoadProgressDialog.Builder(getActivity(), getActivity());
        longBulider = new LongPressShowDialog.Builder(getActivity(), getActivity());
        netBuilder = new ShowNetStatusDialog.Builder(getActivity(), getActivity());
        setState(OpusAdapterNew.FooterState.Normal);
        recyclerView.addOnScrollListener(onScrollListener);
        audio = (AudioManager) getActivity().getSystemService(Service.AUDIO_SERVICE);

        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0); // 设置饱和度
        grayColorFilter = new ColorMatrixColorFilter(cm);
        //这只下载进度框
        progressDialog = new ProgressDialog(getActivity());
        AppListener.getInstance().setOnNoFollowBackListener(new AppListener.OnNoFollowBackListener() {
            @Override
            public void onNoFollowBack() {
                if (isAdded()) {
                    playerPause(currentPosition);
                    isRefresh = true;
                    videoList.clear();
                    pageNo = 1;
                    mPresenter.getFocusOpusList(pageNo + "");
                }else{
                    mAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    protected OpusAdapterNew.FooterState mState = OpusAdapterNew.FooterState.Normal;

    protected void setState(OpusAdapterNew.FooterState mState) {
        this.mState = mState;
        (getActivity()).runOnUiThread(() -> changeAdaperState());
    }

    //改变底部bottom的样式
    protected void changeAdaperState() {
        if (mAdapter != null && mAdapter.mFooterHolder != null) {
            mAdapter.mFooterHolder.setStatus(mState);
        }
    }

    //播放暂停
    public void playerPause(int position) {
        if (mAdapter != null) {
            mAdapter.stopPlay(position);
            return;
        }
        EventBean eventBean = new EventBean();
        eventBean.setType(2);
        EventBus.getDefault().post(eventBean, OpusAdapterNew.EVENT_PAUSE);
    }

    public void onRefreshData() {
        if (VideoUtils.getLocalUserLikeCount() > 0 || VideoUtils.getLocalUserUnLikeCount() > 0) {
            playerPause(currentPosition);
            isRefresh = true;
            videoList.clear();
            pageNo = 1;
            mPresenter.getFocusOpusList(pageNo + "");
            return;
        }
        play();
    }

    public void play() {
        if (!canPlay && !NetUtils.isWiFi()) {
            showNetType(0, "非wifi环境不播放视频", "还是想看");
            playerPause(currentPosition);
            return;
        }
        if (videoList == null || 0 == videoList.size()) {
            return;
        }
//        ObserverManager.getInstance().notifyObserver(ObserverListener.EVENT_CHANGE_OPUS, currentPosition, videoList.get(currentPosition).getProfileId());

        if (mAdapter != null) {
            mHandler.removeMessages(10001);
            mHandler.sendEmptyMessageDelayed(10001, 200);
            return;
        }
        getCostarList();
        EventBean eventBean = new EventBean();
        eventBean.setPosition(currentPosition);
        eventBean.setType(2);
        EventBus.getDefault().post(eventBean, OpusAdapterNew.EVENT_START);
    }
    private void showNetType(int type, String des, String nextStr) {
        if (null == netBuilder) {
            return;
        }
        netStatusDialog = netBuilder.setMessage(type, des, nextStr).setItemClickListener(this).createDialog();
        if (!AppUtils.isShowNetDialog()) return;
        netStatusDialog.show();
    }
    @Override
    protected void getBundle(Bundle bundle) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_focus_opus;
    }

    @Override
    public void onPause() {
        super.onPause();
        playerPause(currentPosition);
        if (videoList==null || videoList.size()==0) return;
        ObserverManager.getInstance().notifyObserver(ObserverListener.EVENT_CHANGE_OPUS, currentPosition, videoList.get(currentPosition).getProfileId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        playerPause(currentPosition);
    }

    @Override
    protected void initData(View rootView) {
        mPresenter.getFocusOpusList(pageNo + "");
        AppListener.getInstance().setOnFocusOpuslistener(new AppListener.OnFocusOpusBackListener() {
            @Override
            public void onFocusOpusBack() {
                if (isAdded()) {
                    mPresenter.getFocusOpusList(pageNo + "");
                }else{
                    mAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    protected OpusPresenter createPresenter() {
        return new OpusPresenter();
    }

    @Override
    protected View initHeader() {
        return null;
    }

    @Override
    protected MyRecycleView createRecycleView() {
        return null;
    }

    @Override
    protected BaseQuickAdapter createAdapter() {
        return null;
    }

    @Override
    protected void refresh() {
    }

    private void initListener() {
        mLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {


            @Override
            public void onPageRelease(boolean isNext, int position) {
                lastPosition = position;
                playerPause(position);
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                currentPosition = position;
                progressBar.setProgress(0);
                getCosView();
                getCostarList();
                if (0 == videoList.size()) {
                    return;
                }

            }

            @Override
            public void onLayoutComplete() {
            }

        });
    }

    RecyclerOnScrollListener onScrollListener = new RecyclerOnScrollListener() {
        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if (mAdapter.mFooterHolder.status == OpusAdapterNew.FooterState.TheEnd) {
                Toast.makeText(getActivity(), "已经是最后一条了", Toast.LENGTH_SHORT).show();
                return;
            }
            setState(OpusAdapterNew.FooterState.Loading);
            mPresenter.getFocusOpusList(pageNo + "");
        }


        @Override
        public void onScrolling(View view) {
            super.onScrolling(view);
        }

        @Override
        public void onScrollStop(View view) {
            super.onScrollStop(view);
            play();
        }
    };

    private void changeZan(boolean type, int index) {
        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null || videoList.size() == 0) {
            return;
        }
        final TextView likeView = itemView.findViewById(R.id.opus_item_view_like);
        final ImageView img = itemView.findViewById(R.id.opus_item_view_like_img);
        int count = 0;
        count = videoList.get(index).getLikeCount();
        if (type) {
            count++;
            videoList.get(index).setIsLike(1);
        } else {
            count--;
            videoList.get(index).setIsLike(-1);
        }
        likeView.setText(StringUtils.formatZanCount(count));

        if (videoList.get(index).getIsLike() == 1) {
            img.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.great_pink_icon));
        } else {
            img.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.great_icon));

        }
        videoList.get(index).setLikeCount(count);

    }


    @Override
    public void observerUpData(int eventType, int index, int id) {
        switch (eventType) {
            case ObserverListener.EVENT_ZAN_ADD://点赞
                if (videoList == null || videoList.get(index) == null || videoList.get(index).getIsLike() == 1) {
                    return;
                }
                mPresenter.getOpusZan(videoList.get(currentPosition).getId() + "", "1", "", "1");
                changeZan(true, currentPosition);
                break;
            case ObserverListener.KEYCODE_VOLUME_UP://音量加
                int max_volume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                int cu_volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                v_progressBar.setVisibility(View.VISIBLE);
                v_progressBar.setMax(max_volume);
                v_progressBar.setProgress(cu_volume);
                Log.e("--volume", "-----add max_volume=" + max_volume);
                Log.e("--volume", "-----add cu_volume=" + cu_volume);
                mHandler.removeMessages(100);
                mHandler.sendEmptyMessageDelayed(100, 3000);
                break;
            case ObserverListener.KEYCODE_VOLUME_DOWN://音量减
                max_volume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                cu_volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                Log.e("--volume", "-----jian max_volume=" + max_volume);
                Log.e("--volume", "-----jian cu_volume=" + cu_volume);
                v_progressBar.setVisibility(View.VISIBLE);
                v_progressBar.setMax(max_volume);
                v_progressBar.setProgress(cu_volume);
                mHandler.removeMessages(100);
                mHandler.sendEmptyMessageDelayed(100, 3000);
                break;
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onLoadMoreRequested() {

    }


    @Override
    public void showLogonResult(HomeBean.DataBean dataBean) {
        if (dataBean == null) {

        } else {
            if (isRefresh) {
                isRefresh = false;
                videoList.clear();
            }
            videoList.addAll(dataBean.getData());
            mAdapter.notifyDataSetChanged();
            if (videoList.size() == dataBean.getTotal() || dataBean.getData() == null || dataBean.getData().size() == 0) {
                setState(OpusAdapterNew.FooterState.TheEnd);
            }
            pageNo++;
        }
        refreshLayout.setRefreshing(false);
        if (videoList.size() == 0) {
            empty_tv.setVisibility(View.VISIBLE);
            lin_empty.setVisibility(View.VISIBLE);
            refreshLayout.setEnabled(false);
            recyclerView.setVisibility(View.INVISIBLE);
            mPresenter.getFocusInfo();
        } else {
            refreshLayout.setEnabled(true);
            recyclerView.setVisibility(View.VISIBLE);
            empty_tv.setVisibility(View.INVISIBLE);
            lin_empty.setVisibility(View.INVISIBLE);
        }
        mHandler.sendEmptyMessageDelayed(10000, 300);
    }

    @Override
    public void showSendResult(int type) {

    }


    @Override
    public void showFail(String msg) {
        super.showFail(msg);
        isCanClickJoin = true;
    }

    @Override
    public void showCostarVideoResult(JoinCostarBean joinCostarBean) {
        if (!isCanClickJoin) return;
        isCanClickJoin = false;
        LogUtils.e(TAG, "开始下载:showCostarVideoResult");
        VideoHelper.getIntence().downVideo(getContext(),mOpusBean.getIsActivity(), joinCostarBean, new VideoHelper.OnVideoHelperDowmVideoListener() {
            @Override
            public void onStartDown() {
                if (progressDialog == null) progressDialog = new ProgressDialog(getActivity());
                progressDialog.show();
                isCanClickJoin = true;
            }

            @Override
            public void onPregress(int pregress) {
                progressDialog.setmProgressbar(pregress);
            }

            @Override
            public void onComplete() {
                progressDialog.disMissDialog();
                VideoHelper.getIntence().setmOpusBean(mOpusBean);
                if ("1".equals(mOpusBean.getIsActivity())) {
                    VideoHelper.getIntence().setActivityId(mOpusBean.getActivityId());
                    Navigate.gotoCostar(getActivity(), mOpusBean.getActivityId());
                } else {
                    VideoHelper.getIntence().setActivityId(-1);
                    Navigate.gotoCostar(getActivity(), -1);
                }
                isCanClickJoin = true;
            }
        });


    }

    @Override
    public void getFollowResult(FollowBean followBean) {
        ToastUtils.showToast(followBean.getRelationShip());
        switch (followBean.getRelationType()) {
          /*  case 0:
                attent.setText("关注");
                break;
            case 1:
                attent.setText("已关注");
                break;
            case 2:
                attent.setText("互相关注");
                break;
            case -1:
                attent.setText("");
                break;*/
        }
    }

    @Override
    public void shoWorkData(HomeBean.DataBean data) {

    }

    @Override
    public void showFound(FoundAtBean data) {

    }

    @Override
    public void showState(BlindResp resp) {

    }

    @Override
    public void showJoinAdd(BlindResp resp) {

    }

    @Override
    public void showVideoInfo(OpusBean opusBean) {

    }

    @Override
    public void showFocusInfo(RecommenResp attentRecommendbeans) {
          if (null ==attentRecommendbeans ||null ==attentRecommendbeans.getData()||0 ==attentRecommendbeans.getData().size()){
              return;
          }

        mAttentAdapter =new FocusAttentionAdapter(getContext(),attentRecommendbeans.getData(),this);
        recycler_view.setAdapter(mAttentAdapter);
    }

    @Override
    public void showLogonResult() {

    }

    @Override
    public void zan(int type, int position, OpusBean opusBean) {
        if (type == 1) {
            if (videoList.get(position).getIsLike() == 1) {
                return;
            }
            mPresenter.getOpusZan(opusBean.getId() + "", "1", "", "1");
            changeZan(true, position);
        } else {
            mPresenter.getOpusZan(opusBean.getId() + "", "1", "", "0");
            changeZan(false, position);
        }
    }

    @Override
    public void share(int position, OpusBean opusBean) {
        ShareFragment shareFragment = ShareFragment.newInstance();
        shareFragment.setLisenter(this);
        if (opusBean.getProfileId() == LogonUtils.getProFildId()) {
            shareFragment.setType("del");
        } else {
            shareFragment.setType("");
        }
        shareFragment.show(getActivity().getSupportFragmentManager(), "myFragment");
    }

    @Override
    public void join(int position, OpusBean opusBean) {
        LogUtils.e(TAG, "开始下载:join");
        if (null == opusBean){
            return;
        }
        mOpusBean = opusBean;
//        mPresenter.getJoin(mOpusBean.getId());
        mPresenter.getCostarVideoInfo(String.valueOf(opusBean.getId()));
    }

    @Override
    public void guanzhu(int position, OpusBean opusBean) {
        if (null == opusBean){
            return;
        }
        mPresenter.loginFollowFans(opusBean.getProfileId() + "");
        Toast.makeText(getActivity(), "点击关注", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void comm(int position, OpusBean opusBean) {
        CommentListDialogFragment fragment = CommentListDialogFragment.newInstance();
        fragment.setParam(position, opusBean.getId() + "", opusBean.getProfileId(), opusBean.getProfileName());
        fragment.setCommLisenter(this);
        fragment.show(getActivity().getSupportFragmentManager(), "myFragment");
    }

    @Override
    public void playSuccess(int position) {
    }

    @Override
    public void awkward(int position, OpusBean opusBean) {
        ObserverManager.getInstance().notifyObserver(ObserverListener.EVENT_AWKWARD, position, opusBean.getId());
    }

    @Override
    public void longPress(int position, OpusBean opusBean) {
        LogUtils.e("test25", "opusBean.getProfileId()=" + opusBean.getProfileId());
        LogUtils.e("test25", "LogonUtils.getProFildId()=" + LogonUtils.getProFildId());
        if (opusBean.getProfileId() == LogonUtils.getProFildId()) {
            longPressShowDialog = longBulider.setMessage(position, opusBean, 1).setItemClickListener(this).createDialog();
            longPressShowDialog.show();
        } else {
            longPressShowDialog = longBulider.setMessage(position, opusBean, 0).setItemClickListener(this).createDialog();
            longPressShowDialog.show();
        }
    }

    @Override
    public void showPlayProgress(int position, IMediaController.MediaPlayerControl mediaPlayerControl) {
        mPlayer = mediaPlayerControl;
        mHandler.removeMessages(SHOW_PROGRESS);
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
    }


    @Override
    public void share(SHARE_MEDIA share_media, int type) {
        showLoading("正在分享...");

        OpusBean opusBean = videoList.get(currentPosition);
        ShareUtils.getIntance().shareVideo(getActivity(), share_media, String.valueOf(opusBean.getId()), opusBean.getVideoUrl(), opusBean.getVideoCverUrl(), opusBean.getProfileName() + ShareUtils.shareTitle, (TextUtils.isEmpty(opusBean.getVideoDesp()) ? ShareUtils.shareDes : opusBean.getVideoDesp()), this);

    }

    @Override
    public void other(int type) {
        OpusBean opusBean = videoList.get(currentPosition);
        switch (type) {
            case 1://复制链接
                ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                String path = opusBean.getVideoUrl();
                ClipData myClip = ClipData.newPlainText("text", path);
                cm.setPrimaryClip(myClip);
                Toast.makeText(getActivity(), "链接已经复制到剪切板", Toast.LENGTH_SHORT).show();
                break;
            case 2:// 下载
                DownLoadVideo(opusBean.getVideoUrl());
                break;
            case 3://不感兴趣
                videoList.remove(opusBean);
                if (null != mAdapter) {
                    mAdapter.notifyDataSetChanged();
                }
                initPlay();
                mPresenter.getLoseInterest(opusBean.getId() + "", System.currentTimeMillis() + "");
                break;
            case 4:
                Navigate.startReportList(getContext(), 1, opusBean.getId());
                break;
            case 5://删除
                onDel(currentPosition, opusBean);
                break;
        }
    }

    // 下载
    private void DownLoadVideo(String url) {
        downLoadProgressDialog = builder.setUrl(url).createDialog();
        downLoadProgressDialog.show();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onShareFinish() {
        hideLoading();
    }

    @Override
    public void onShareSuccess() {

    }


    public void onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                audio.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_RAISE,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                audio.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_LOWER,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
            default:
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            long pos;
            switch (msg.what) {
                case SHOW_PROGRESS:
                    if (mPlayer == null || !mPlayer.isPlaying()) {
                        return;
                    }
                    pos = setProgress();
                    mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, Constant.DEPLAY);
                    break;
                case 100:
                    if (v_progressBar != null && v_progressBar.getVisibility() == View.VISIBLE) {
                        v_progressBar.setVisibility(View.INVISIBLE);
                    }
                    break;
                case 10000:
                    play();
                    break;
                case 10001:
                    if (mAdapter != null) {
                        mAdapter.startPlay(currentPosition);
                    }
                    break;
            }
        }
    };

    private long setProgress() {
        if (mPlayer == null) {
            return 0;
        }

        long position = mPlayer.getCurrentPosition();
        long duration = mPlayer.getDuration();
        if (progressBar != null) {
            if (duration > 0) {
                progressBar.setProgress((int) position);
                progressBar.setMax((int) duration);
            }
        }
        if (position + 200 >= duration) {
            getCostarList();
        }
        showCurrentCostarPro((int) position);
        return position;
    }

    @Override
    public void onUnlike(int position, OpusBean opusBean) {
        videoList.remove(opusBean);
        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
        initPlay();
        mPresenter.getLoseInterest(opusBean.getId() + "", System.currentTimeMillis() + "");
    }

    void initPlay() {
        if (currentPosition > 0 && currentPosition < videoList.size()) {
            mLayoutManager.scrollToPositionWithOffset(currentPosition, 0);
            mLayoutManager.setStackFromEnd(true);
        }
        play();
    }

    @Override
    public void onReport(int position, OpusBean opusBean) {
        Navigate.startReportList(getContext(), 1, opusBean.getId());
    }

    @Override
    public void onDel(int position, OpusBean opusBean) {
        try {
            mAdapter.stopPlay(position);
            videoList.remove(position);
            mAdapter.notifyDataSetChanged();
            mPresenter.del(opusBean.getId() + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void commSuccess(int position, int type) {
        if (position > videoList.size()) {
            return;
        }
        int count = videoList.get(position).getCommentCount();
        if (type == 1) {
            count++;
        } else {
            count--;
        }
        videoList.get(position).setCommentCount(count);

        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null) {
            return;
        }
        final TextView tv_comment = itemView.findViewById(R.id.opus_item_view_comment);
        tv_comment.setText(StringUtils.formatZanCount(count));
    }

    boolean sharkFlag = true;

    //摇一摇
    public void shark() {
        sharkFlag = !sharkFlag;
        if (mAdapter != null) {
            mAdapter.setSharkFlag(sharkFlag);
            mAdapter.notifyDataSetChanged();
            play();
        }

    }

    public void getCostarList() {
        videoSectionList.clear();
        if (videoList == null || videoList.size() == 0 || currentPosition > videoList.size()) {
            return;
        }
        int proFildId = videoList.get(currentPosition).getProfileId();
        if (cosRel == null || cosCircleImageView == null || cosGuanzhu == null || cosTag == null) {
            getCosView();
        }
        for (VideoSection v : videoList.get(currentPosition).getVideoSectionInfoList()) {
            if (v.getCostarProfileId() != proFildId) {
                videoSectionList.add(v);
            }
        }
        if (videoSectionList.size() == 0) {
            cosRel.setVisibility(View.GONE);
        }
        Log.e("costar", "proFildId=" + proFildId + "   costar  count=" + videoSectionList.size());
    }

    public void showCurrentCostarPro(int position) {

        if (cosRel == null || cosCircleImageView == null || cosGuanzhu == null || cosTag == null) {
            getCosView();
        }
        if (videoSectionList == null || videoSectionList.size() == 0) {
            opus_item_view_user_img1.setColorFilter(null);
            cosCircleImageView.setColorFilter(grayColorFilter);
            return;
        }
        int s_time = 0;
        int e_time = 0;
        VideoSection videoSection = null;
        videoSection = videoSectionList.get(0);
        if (videoSection == null) {
            return;
        }
        e_time = videoSection.getSectionEndPoint();

        if (e_time < position) {
            videoSectionList.remove(0);
            if (videoSectionList.size() > 0) {
                videoSection = videoSectionList.get(0);
            }
        }
        if (videoSection == null) {
            return;
        }
        s_time = videoSection.getSectionStartPoint();
        e_time = videoSection.getSectionEndPoint();

        int cosUserId = videoSection.getCostarProfileId();
        Log.e("test41", s_time + "--" + position + "--" + e_time);
        if (s_time > position) {
            if (cosTag.getTag() == null || cosUserId != Integer.parseInt(cosTag.getTag().toString())) {
                cosTag.setTag(cosUserId);
                ImageUtils.LoadImage(getActivity(), videoSection.getCostarProfileAvatar(), cosCircleImageView);
                if (videoSection.getIsAttentionCostar() == 1) {
                    cosGuanzhu.setVisibility(View.INVISIBLE);
                } else {
                    cosGuanzhu.setVisibility(View.VISIBLE);
                }
                if (videoSection.getCostarTag() != null && !"".equals(videoSection.getCostarTag())) {
                    cosTag.setText(videoSection.getCostarTag());
                    cosTag.setVisibility(View.INVISIBLE);
                } else {
                    cosTag.setVisibility(View.INVISIBLE);
                }
            }
            cosCircleImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("user_id", cosUserId);
                    bundle.putInt("tag", 1);
                    TerminalActivity.showFragment(getActivity(), HomeMineFragment.class, bundle);
                }
            });
            cosGuanzhu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPresenter.loginFollowFans(cosUserId + "");
                    handleCosGuanzhu(cosUserId);
                    cosGuanzhu.setVisibility(View.INVISIBLE);
                }
            });
            tofocus(cosUserId);
            opus_item_view_user_img1.setColorFilter(null);
            cosCircleImageView.setColorFilter(grayColorFilter);
            Log.e("test41", "------未开始播放");
            cosRel.setVisibility(View.VISIBLE);
            return;
        }
        if (e_time > position) {
            if (cosTag.getTag() == null || cosUserId != Integer.parseInt(cosTag.getTag().toString())) {
                cosTag.setTag(cosUserId);
                ImageUtils.LoadImage(getActivity(), videoSection.getCostarProfileAvatar(), cosCircleImageView);
                if (videoSection.getIsAttentionCostar() == 1) {
                    cosGuanzhu.setVisibility(View.INVISIBLE);
                } else {
                    cosGuanzhu.setVisibility(View.VISIBLE);
                }
                if (videoSection.getCostarTag() != null && !"".equals(videoSection.getCostarTag())) {
                    cosTag.setText(videoSection.getCostarTag());
                    cosTag.setVisibility(View.INVISIBLE);
                } else {
                    cosTag.setVisibility(View.INVISIBLE);
                }
            }
            tofocus(cosUserId);
            cosCircleImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("user_id", cosUserId);
                    bundle.putInt("tag", 1);
                    TerminalActivity.showFragment(getActivity(), HomeMineFragment.class, bundle);
                }
            });
            cosGuanzhu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPresenter.loginFollowFans(cosUserId + "");
                    handleCosGuanzhu(cosUserId);
                    cosGuanzhu.setVisibility(View.INVISIBLE);
                }
            });
            opus_item_view_user_img1.setColorFilter(grayColorFilter);
            cosCircleImageView.setColorFilter(null);
            Log.e("test41", "---开始播放");
            cosRel.setVisibility(View.VISIBLE);
            return;
        }

    }

    void tofocus(int cosUserId){
        AppListener.getInstance().setOnFocusBackListener(new AppListener.OnFocusBackListener() {
            @Override
            public void onFocusBack(String focus) {
                mProfileId = focus.split("::");
            }
        });
        if (null !=mProfileId) {
            if (mProfileId[0].equals(String.valueOf(cosUserId))) {
                if ("1".equals(mProfileId[1])) {
                    cosGuanzhu.setVisibility(View.GONE);
                } else if ("2".equals(mProfileId[1])) {
                    cosGuanzhu.setVisibility(View.VISIBLE);
                }
            }
        }
    }
    //获取合演view
    public void getCosView() {
        if (recyclerView == null || videoList.size() == 0) {
            return;
        }
        View itemView = recyclerView.getChildAt(0);
        if (itemView == null) {
            return;
        }
        cosRel = itemView.findViewById(R.id.opus_item_view_user_join_rel);
        cosCircleImageView = itemView.findViewById(R.id.opus_item_view_user_join);
        opus_item_view_user_img1 = itemView.findViewById(R.id.opus_item_view_user_img1);
        cosGuanzhu = itemView.findViewById(R.id.opus_item_view_user_joi_guanzhu);
        cosTag = itemView.findViewById(R.id.opus_item_view_user_join_des);
    }

    //合演关注 改变关注状态
    public void handleCosGuanzhu(int id) {
        if (videoList.get(currentPosition).getVideoSectionInfoList() != null) {
            for (int i = 0; i < videoList.get(currentPosition).getVideoSectionInfoList().size(); i++) {
                if (videoList.get(currentPosition).getVideoSectionInfoList().get(i).getCostarProfileId() == id) {
                    videoList.get(currentPosition).getVideoSectionInfoList().get(i).setIsAttentionCostar(1);
                }
            }
        }
    }

    @Override
    public void attentFocus(int position, AttentRecommendbean bean) {
        if (null == bean){
            return;
        }
        if (0 == mAttentAdapter.getItem(position).isAttention){
            mAttentAdapter.getItem(position).isAttention = 1;
            mAttentAdapter.notifyDataSetChanged();
            mPresenter.loginFollowFans(bean.profileId + "");
        }else{
            mAttentAdapter.getItem(position).isAttention = 0;
            mAttentAdapter.notifyDataSetChanged();
            mPresenter.loginNoFollow(bean.profileId+"",position);
        }
        AppListener.OnAttentFocusBackListener listener = AppListener.getInstance().getOnAttentFocusBackListener();
        if (null !=listener){
            listener.onAttentBack();
        }
    }

    @Override
    public void clickimage(int position, AttentRecommendbean bean) {
        if (null == bean){
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putInt("user_id", bean.profileId);
        bundle.putInt(Constant.TAG, 1);
        TerminalActivity.showFragment(getContext(), HomeMineFragment.class, bundle);
    }

    @Override
    public void showNoFollowResult(FollowBean followBean, int position) {
        Toast.makeText(getContext(), "取消关注成功", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPlay() {
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
        canPlay = true;
        play();
    }

    @Override
    public void onRefreshPlay() {
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
        play();
    }

    @Override
    public void onNetRefresh() {
        mPresenter.getFocusOpusList(pageNo + "");
        if (netStatusDialog != null)
            netStatusDialog.dismiss();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.cosfun_iv:
                Navigate.gotoSearchActivity(getActivity());
                break;
        }
    }
    @Override
    public void remmend(int position, OpusBean opusBean) {
        if (StringUtils.isFastDoubleClick(500)){
            return;
        }
        manager = 2;
        mPresenter.checkAndRemmend(String.valueOf(opusBean.getId()),2);
    }

    @Override
    public void checkAndPass(int position, OpusBean opusBean) {
        if (StringUtils.isFastDoubleClick(500)){
            return;
        }
        manager = 1;
        mPresenter.checkAndRemmend(String.valueOf(opusBean.getId()),1);
    }
    @Override
    public void showCheckAndRemmend() {
        if (2 == manager){
            showToast(getResources().getString(R.string.recommend_success));
        }else if (1 == manager){
            showToast(getResources().getString(R.string.check_success));
        }
    }
    @Override
    public void startPlay() {
        if (null == mHandler){
            return;
        }
        mHandler.removeMessages(SHOW_PROGRESS);
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 100);
    }
}
